/**
 * 区域设置 列表页
 *
 * 作者 admin
 * 日期 2024-07-31 14:35:47
 */
layui.use(['jquery', 'laydate', 'febs', 'form', 'table', 'commonJS', 'validate'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        febs = layui.febs,
        form = layui.form,
        table = layui.table,
        commonJS = layui.commonJS,
        validate = layui.validate,
        $view = $('#febs-baseArea'),
        $query = $view.find('#query'),
        $scheduleView = $view.find('#scheduleView'),
        $add = $view.find('#add'),
        $addWork = $view.find('#addWork'),
        $searchForm = $view.find('#baseArea-table-form'),
        tableIns;

    form.verify(validate);
    form.render();

    initTable();
    initDate();

    function initDate() {
        //初始化日期控件
        laydate.render({
            elem: '#febs-form-group-date',
            // type: 'datetime',
            value: new Date(),
            format:'yyyy-MM-dd',
            btns:['now','confirm'],
            isInitValue: true
        })
    }

    function initTable() {
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'baseAreaTable',
            url: ctx + 'baseArea/list',
            height: getTableHeight(),
            where: getQueryParams(),
            skin: '',
            cols: [[
                {type: 'numbers', title: '序号'},
                {field: 'areaName', title: '区域名称', minWidth: 120,style:'color:#01aaed;cursor:pointer',event:'detail'},
                {field: 'areaType', title: '区域类型', width: 120 ,align:'center',templet:function (d){
                        if(d.areaType === '1'){
                            return  '<span class="layui-badge febs-tag-green">'+ d.areaTypeName +'</span>';
                        }else if (d.areaType === '2') {
                            return  '<span class="layui-badge febs-tag-blue">'+ d.areaTypeName +'</span>';
                        }
                }},
                // {field: 'areaCoordinate', title: '位置信息', minWidth: 120},
                {field: 'sort', title: '排序', width: 80,align:'center'},
                {field: 'status', title: '状态', width: 100,align:'center',toolbar: '#status-bar' ,},
                {field: 'morningMan', title: '白班', width: 120,align:'center'},
                {field: 'middleMan', title: '中班', width: 120,align:'center'},
                {field: 'nightMan', title: '晚班', width: 120,align:'center'},
                {title: '操作', toolbar: '#are-option',align:'center', width: 160}
            ]],
            toolbar: '#baseArea-toolbar',
            defaultToolbar: []
        });
    }

    table.on('sort(baseAreaTable)', function (obj) {
        tableIns.reload({
            initSort: obj,
            where: $.extend(getQueryParams(), {
                field: obj.field,
                order: obj.type
            }),
            autoSort: true
        });
    });

    function reloadPage(curr) {
        var _curr = $view.find(".layui-laypage-em").next().html();
        if (!!curr) {
            _curr = curr;
        }
        tableIns.reload({where: getQueryParams(), page: {curr: _curr}});
    }

    $query.on('click', function () {
        reloadPage(1);
    });

    function getQueryParams() {
        // console.log("areaName=",$searchForm.find('input[name="areaName"]').val());
        // console.log("scheduleDate=",$searchForm.find('input[name="schedulingDate"]').val());
        // console.log("tenantId=",$searchForm.find("select[name='tenantId']").find("option:selected").val());
        return {
            areaName: $searchForm.find('input[name="areaName"]').val(),
            schedulingDate: $searchForm.find('input[name="schedulingDate"]').val(),
            tenantId: $searchForm.find("select[name='tenantId']").find("option:selected").val(),
            status: $searchForm.find("select[name='status']").find("option:selected").val(),
            invalidate_ie_cache: new Date()
        };

    }

    table.on('toolbar(baseAreaTable)', function (obj) {
        var layEvent = obj.event;
        // console.log('时间'+obj.event);
        if(layEvent === 'add'){
            febs.modal.open('新增区域', 'baseArea/add', {
                btn: ['提交','取消'],
                area: [$(window).width() <= 750 ? '90%' : '700px','520px'],
                yes: function (index, layero) {
                    $('#baseArea-edit').find('#submit').trigger('click');
                },
                data:{
                    tenantId: $searchForm.find('select[name="tenantId"]').val()
                }
            });

        }else if (layEvent === 'addWork') {
            var tenantId = $searchForm.find("select[name='tenantId']").find("option:selected").val();
            febs.modal.open('新增排班', 'baseAreaScheduling/add/'+tenantId, {
                btn: ['提交','取消'],
                area: $(window).width() <= 750 ? '90%' : ['1200px', '650px'],
                yes: function (index, layero) {
                    $('#baseAreaScheduling-edit').find('#submit').trigger('click');
                },
                data:{
                    tenantId: tenantId
                }
            });

        }else if (layEvent === 'scheduleView') {
            febs.modal.open('排班总览', 'baseAreaScheduling', {
                // btn: ['取消'],
                area: $(window).width() <= 750 ? ['95%', '85%']: ['1200px', '650px'],
                yes: function (index, layero) {
                    // $('#baseAreaScheduling-edit').find('#submit').trigger('click');
                },
            });

        }else if (layEvent === 'scheduleImport') {


        }else if (layEvent === 'scheduleExport') {


        }
    });

    table.on('tool(baseAreaTable)', function (obj) {
        //表格编辑删除事件
        var areaId = obj.data.areaId;
        var layEvent = obj.event;
        if (layEvent === 'edit') {
            febs.modal.open('修改区域', 'baseArea/update/' + areaId, {
                btn: ['提交','取消'],
                area: [$(window).width() <= 750 ? '90%' :  '700px','520px'],
                yes: function (index, layero) {
                    $('#baseArea-edit').find('#submit').trigger('click');
                },
            });
        } else if (layEvent === 'del') {
            febs.get(ctx + 'baseArea/deleteCheck/' + areaId, null, function (r) {
                // console.log("删除检查"+r.data);
                if(r.data){
                    febs.modal.confirm('删除区域', '确定删除所选区域？', function () {
                        deleteAres(areaId);
                    });
                }else {
                    febs.modal.confirm('删除区域', '所选区域存在排班信息，确定删除所选区域？', function () {
                        deleteAres(areaId);
                    });
                }
            });
        } else if(layEvent === 'editWork'){
            var date = $searchForm.find('input[name="schedulingDate"]').val();
            febs.modal.open('编辑排班', 'baseAreaScheduling/update/'+areaId+'/'+date, {
                btn: ['提交','取消'],
                area: $(window).width() <= 750 ? '90%' : ['1200px', '650px'],
                yes: function (index, layero) {
                    $('#baseAreaScheduling-edit').find('#submit').trigger('click');
                },
                data:{
                    tenantId: tenantId
                }
            });
        }else if(obj.event === 'detail'){
            febs.modal.open('区域地图', 'baseArea/baseAreaViewMap/'+ areaId, {
                btn: ['关闭'],
                area: $(window).width() <= 750 ?  ['85%', '80%']: ['1300px', '95%'],
                shadeClose:true,
                yes: function (index, layero) {
                    layer.closeAll();
                },
                cancel:function () {
                },
                data:{
                    areaCoordinate : []
                }
            });
        }
    });

    function deleteAres(areaId) {
        febs.get(ctx + 'baseArea/delete/' + areaId, null, function () {
            febs.alert.success('删除区域成功');
            $query.trigger('click');
        })
    }

    form.on('switch(areaStatus)', function (obj) {
        //区域状态控制点击事件
        var checked = obj.elem.checked;
        var status;
        if (checked) {
            status = "1";
        } else {
            status = "0";
        }
        //获取该控件所在行
        var index = obj.othis.parents('tr').eq(0).data('index');
        //获取表中所有数据 按行取数据及其 postId
        var id =  table.cache['baseAreaTable'][index].areaId;
        // console.log("区域Id"+id);
        febs.modal.confirm('更改区域状态', '确认更改区域状态',function (){
            updateStatus(id,status);
        },function (){
            obj.elem.checked = !checked;
            layer.closeAll();
            form.render('checkbox');
        });

    });

    function updateStatus(id,status) {
        //更新岗位状态
        let model={
            areaId : id,
            status : status
        }
        febs.post(ctx + 'baseArea/updateStatus', model, function () {
            febs.alert.success('修改区域状态成功');
        })
    }

    function getTableHeight() {
        return commonJS.calcTableHeight();
    }

    $(window).resize(function () {
        tableIns.reload({height: getTableHeight()});
    });
});